package com.snack.shop.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snack.shop.common.Result;
import com.snack.shop.dto.CreateOrderParam;
import com.snack.shop.dto.ReorderItemDTO;
import com.snack.shop.entity.Order;
import com.snack.shop.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单控制器
 */
@Tag(name = "订单管理")
@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    @Operation(summary = "创建订单")
    @PostMapping("/create")
    public Result<Order> create(@Validated @RequestBody CreateOrderParam param) {
        Long userId = StpUtil.getLoginIdAsLong();
        Order order = orderService.createOrder(userId, param);
        return Result.success(order);
    }

    @Operation(summary = "分页查询订单列表")
    @GetMapping("/page")
    public Result<Page<Order>> page(
        @Parameter(description = "订单状态（null表示全部）") @RequestParam(required = false) Integer status,
        @Parameter(description = "订单类型（null表示全部，1-零食订单，2/3/4-代取订单）") @RequestParam(required = false) Integer orderType,
        @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Integer current,
        @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
        @Parameter(description = "关键词（订单号/地址/备注模糊搜索）") @RequestParam(required = false) String keyword
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 判断用户角色
        List<String> roleList = StpUtil.getRoleList();
        Page<Order> page;
        
        if (roleList.contains("merchant")) {
            // 商家：查询所有订单（通常只查零食订单orderType=1，代取订单是C2C不归商家管）
            page = orderService.pageAll(status, orderType, current, size, keyword);
        } else {
            // 普通用户：只查询自己的订单z
            page = orderService.pageByUser(userId, status, orderType, current, size, keyword);
        }
        
        return Result.success(page);
    }

    @Operation(summary = "获取订单详情")
    @GetMapping("/{id}")
    public Result<Order> getDetail(@PathVariable Long id) {
        Order order = orderService.getDetail(id);
        return Result.success(order);
    }

    // 旧的余额支付接口（已废弃，现在只支持微信支付）
    // 微信支付使用 PaymentController 中的接口
    // @Operation(summary = "支付订单")
    // @PostMapping("/{id}/pay")
    // public Result<Void> pay(@PathVariable Long id) {
    //     Long userId = StpUtil.getLoginIdAsLong();
    //     orderService.pay(userId, id);
    //     return Result.success();
    // }

    @Operation(summary = "取消订单")
    @PostMapping("/{id}/cancel")
    public Result<Void> cancel(
        @PathVariable Long id,
        @Parameter(description = "取消原因") @RequestParam(required = false) String reason
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        orderService.cancel(userId, id, reason);
        return Result.success();
    }

    @Operation(summary = "确认收货")
    @PostMapping("/{id}/receive")
    public Result<Void> confirmReceive(@PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        orderService.confirmReceive(userId, id);
        return Result.success();
    }

    @Operation(summary = "商家接单")
    @PostMapping("/{id}/accept")
    public Result<Void> acceptOrder(@PathVariable Long id) {
        orderService.acceptOrder(id);
        return Result.success();
    }

    @Operation(summary = "商家拒单")
    @PostMapping("/{id}/reject")
    public Result<Void> rejectOrder(
        @PathVariable Long id,
        @Parameter(description = "拒单原因") @RequestParam(required = false) String reason
    ) {
        orderService.rejectOrder(id, reason);
        return Result.success();
    }

    @Operation(summary = "商家完成订单")
    @PostMapping("/{id}/finish")
    public Result<Void> finishOrder(@PathVariable Long id) {
        orderService.finishOrder(id);
        return Result.success();
    }

    @Operation(summary = "申请退款")
    @PostMapping("/{id}/refund/apply")
    public Result<RefundApplyResult> applyRefund(
        @PathVariable Long id,
        @Parameter(description = "退款原因") @RequestBody RefundApplyRequest request
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean needApproval = orderService.applyRefund(userId, id, request.getReason());
        
        RefundApplyResult result = new RefundApplyResult();
        result.setNeedApproval(needApproval);
        result.setMessage(needApproval ? "退款申请已提交，等待商家审核" : "退款申请已处理");
        
        return Result.success(result);
    }

    @Operation(summary = "查询退款状态")
    @GetMapping("/{id}/refund/status")
    public Result<Order> getRefundStatus(@PathVariable Long id) {
        Order order = orderService.getRefundStatus(id);
        return Result.success(order);
    }

    @Operation(summary = "获取再来一单复购清单")
    @GetMapping("/{id}/reorder-items")
    public Result<java.util.List<ReorderItemDTO>> getReorderItems(@PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        List<ReorderItemDTO> items = orderService.getReorderItems(userId, id);
        return Result.success(items);
    }

    @Operation(summary = "商家删除订单")
    @SaCheckRole("merchant")
    @DeleteMapping("/{id}")
    public Result<Void> deleteOrder(@PathVariable Long id) {
        orderService.deleteOrderByMerchant(id);
        return Result.success();
    }

    /**
     * 退款申请请求参数
     */
    public static class RefundApplyRequest {
        private String reason;
        
        public String getReason() {
            return reason;
        }
        
        public void setReason(String reason) {
            this.reason = reason;
        }
    }

    /**
     * 退款申请结果
     */
    public static class RefundApplyResult {
        private Boolean needApproval;
        private String message;
        
        public Boolean getNeedApproval() {
            return needApproval;
        }
        
        public void setNeedApproval(Boolean needApproval) {
            this.needApproval = needApproval;
        }
        
        public String getMessage() {
            return message;
        }
        
        public void setMessage(String message) {
            this.message = message;
        }
    }
}

